export const SET_TOKEN = (token: string) => {
  localStorage.setItem('TOKEN', token)
}

export const GET_TOKEN = () => {
  return localStorage.getItem('TOKEN')
}

// 本地存储删除TOKEN
export const REMOVE_TOKEN = () => {
  localStorage.removeItem('TOKEN')
}

interface TreeNode {
  [key: string]: any

  children?: TreeNode[]
  _level?: number
}

/**
 * Converts flat array to tree structure
 * @param data Flat array of nodes
 * @param id Key name for node identifier (default: 'id')
 * @param pid Key name for parent identifier (default: 'parentId')
 * @returns Tree structure array
 */
export function treeDataTranslate<T extends TreeNode>(
  data: T[],
  id: string = 'id',
  pid: string = 'parentId',
): T[] {
  const nodeMap = new Map<string | number, T>()
  const tree: T[] = []

  // Create map of all nodes
  data.forEach((node) => {
    nodeMap.set(node[id], { ...node })
  })

  // Build tree structure
  data.forEach((node) => {
    const parentNode = nodeMap.get(node[pid])

    if (parentNode && node[id] !== node[pid]) {
      if (!parentNode.children) {
        parentNode.children = []
      }

      parentNode._level = parentNode._level ?? 1
      const currentNode = nodeMap.get(node[id])!
      currentNode._level = parentNode._level + 1

      parentNode.children.push(currentNode)
    } else {
      tree.push(nodeMap.get(node[id])!)
    }
  })

  return tree
}
